import React from 'react';
import { Button, Table } from 'antd';
import { IconFontTool } from '../../../components/IconFont';
import { cloneDeep } from 'lodash';

export default function ConfigTable(props) {
  const {
    isAdd = true,
    isOrder = true,
    isDelete = true,
    cusColumns = [],
    cusOperates = [],
    defaultData = {},
    data = [],
    onChange,
    beforeDeleteMethod,
    scroll,
  } = props;

  const handleAdd = () => {
    const temp = [...data];
    temp.push(cloneDeep(defaultData));
    onChange(temp);
  };

  const handleSort = (type, index) => {
    const temp = [...data];
    const tempIndex = temp[index];
    if (type) {
      if (index === data.length - 1) return;
      temp[index] = temp[index + 1];
      temp[index + 1] = tempIndex;
    } else {
      if (!index) return;
      temp[index] = temp[index - 1];
      temp[index - 1] = tempIndex;
    }
    onChange(temp);
  };

  const handleDel = (_, index) => {
    const returnValue = beforeDeleteMethod && beforeDeleteMethod(index);
    if (!returnValue) {
      const temp = [...data];
      temp.splice(index, 1);
      onChange(temp);
    }
  };

  const defaultColumns = [
    {
      title: '顺序',
      dataIndex: 'order',
      render: (_, __, index) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <IconFontTool
            type={'iconsort-arrow-up-'}
            style={!index ? { color: '#f5f5f5' } : {}}
            onClick={() => handleSort(0, index)}
          />
          <IconFontTool
            type={'iconsort-arrow-down-'}
            style={index === data.length - 1 ? { color: '#f5f5f5' } : {}}
            onClick={() => handleSort(1, index)}
          />
        </div>
      ),
    },
  ];

  const defaultOperate =
    cusOperates.length || isDelete
      ? [
          {
            title: '操作',
            render: (_, record, index) =>
              [...cusOperates, { label: '删除', method: handleDel, display: () => isDelete }].filter(Boolean).map(
                ({ label, method, display }, index1) =>
                  (display ? display(record, index) : true) && (
                    <Button key={index1} type='link' onClick={() => method(record, index)}>
                      {label}
                    </Button>
                  )
              ),
          },
        ]
      : [];

  const getNewColums = () => {
    const tempColums = isOrder ? defaultColumns : [];
    return [...tempColums, ...cusColumns, ...defaultOperate].filter(Boolean);
  };

  return (
    <div>
      {isAdd && <Button onClick={handleAdd}>添加</Button>}
      <Table
        columns={getNewColums()}
        dataSource={data}
        rowKey={(record, index) => index}
        pagination={false}
        className='config_table'
        scroll={scroll}
      />
    </div>
  );
}
